import requests
import pandas as pd
import json

# 确保正确导入 APIClient 类
class APIClient:
    """
    A client class to interact with the REST API.
    """

    def __init__(self, base_url=None):
        """
        Initialize the API client.

        Args:
            base_url (str): The base URL of the API. If not provided, defaults to a fixed URL.
        """
        if base_url is None:
            self.base_url = "http://114.242.246.245:18095/mdrbase-api/prod/rpt-arc/api"
        else:
            self.base_url = base_url

    def call_api(self, path, params):
        """
        Call the API with the specified path and parameters.

        Args:
            path (str): The API path.
            params (dict): The parameters to send in the request.

        Returns:
            dict: The response data if successful.
            None: If the request fails.
        """
        url = f"{self.base_url}/dataset/call"
        payload = {
            "path": path,
            "params": params
        }

        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()  # Raise an error for HTTP codes 4xx/5xx
            data = response.json()
            if data.get("success"):
                return data
            else:
                print(f"API returned an error: {data.get('message')}")
                return None
        except requests.RequestException as e:
            print(f"An error occurred while making the request: {e}")
            return None

    def parse_to_dataframe(self, response):
        """
        Parse the API response into a Pandas DataFrame.

        Args:
            response (dict): The API response.

        Returns:
            pd.DataFrame: The data in DataFrame format.
        """
        if not response or "rows" not in response:
            print("No data available to convert to DataFrame.")
            return pd.DataFrame()

        rows = response.get("rows", [])
        return pd.DataFrame(rows)


class MetricsService(APIClient):
    """
    A service class that inherits from APIClient to interact with the KPI metrics API.
    """

    def __init__(self, base_url=None):
        # Using the parent class initializer
        super().__init__(base_url)
        self.path = "/标版/接口/HQLForAI.biz"
        
    def get_kpis(self, params):
        """
        Fetch KPI data from the API with the given parameters.

        Args:
            start_date (str): Start date for the KPI data.
            end_date (str): End date for the KPI data.
            kpis (str): The KPIs to query.

        Returns:
            pd.DataFrame: A DataFrame containing the KPI data.
        """

        # Call the API and return the response as a DataFrame
        response = self.call_api(self.path, params)
        return self.parse_to_dataframe(response)


# Usage example:
if __name__ == "__main__":
    # Initialize the MetricsService client (inherits from APIClient)
    client = MetricsService()

    # Define parameters
    params = {
            "startDate": '2022-01-01',
            "endDate": '2025-01-01',
            "kpis": 'S0010001 as kpi1'
        }

    # Get KPI data
    df = client.get_kpis(params)

    # Print the DataFrame
    if not df.empty:
        print("KPI Data:")
        print(df)
    else:
        print("No data retrieved from the API.")